package com.xhwl.logistics.util;


import com.alibaba.fastjson.JSONObject;
import com.xhwl.common.enums.CodeEnum;
import com.xhwl.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 响应和请求的工具类
 */
@Slf4j
public class ServletUtils {

    private static final String encoding_utf8 = "UTF-8";
    private static final String code = "code";
    private static final String message = "message";
    private static final String result = "result";
    private static final String state = "state";

    /**
     * 读取请求类中的请求参数
     */
    public static String onGettingRequestBody(HttpServletRequest request) {
        try {
            BufferedReader reader = request.getReader();
            char[] buf = new char[512];
            int len = 0;
            StringBuffer contentBuffer = new StringBuffer();
            while ((len = reader.read(buf)) != -1) {
                contentBuffer.append(buf, 0, len);
            }
            return contentBuffer.toString();
        } catch (Exception e) {
            throw new BusinessException("获取请求参数异常");
        }
    }

    /**
     * 自定义返回结果
     * @param response
     * @param respData
     */
    public static void RespToWrite(HttpServletResponse response, Map<String, Object> respData){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        try {
            response.getWriter().write(JSONObject.toJSONString(respData));
        } catch (Exception e) {
            throw new BusinessException("(RespToSuccessMapStrObj)向响应类中写入成功信息失败！");
        }
    }

    /**
     * 返回给前端正确的信息，兴海格式，结果为null
     */
    public static void RespToSuccess(HttpServletResponse response){
        Map<String, Object> respData = CommonResp();
        RespToJSON(response, null);
        try {
            response.getWriter().write(JSONObject.toJSONString(respData));
        } catch (Exception e) {
            throw new BusinessException("(RespToSuccess)向响应类中写入成功信息失败！");
        }
    }

    /**
     * 返回给前端正确的信息，兴海格式，结果为Map<String,Object>
     */
    public static void RespToSuccessMapStrObj(Map<String, Object> resultData, HttpServletResponse response){
        Map<String, Object> respData = CommonResp();
        respData.put(result, resultData);
        RespToJSON(response, null);
        try {
            response.getWriter().write(JSONObject.toJSONString(respData));
        } catch (Exception e) {
            throw new BusinessException("(RespToSuccessMapStrObj)向响应类中写入成功信息失败！");
        }
    }

    /**
     * 需要响应类返回JSON数据时，需要对response进行一些初始化
     * 处理响应类，使其返回值未JSON数据
     */
    private static void RespToJSON(HttpServletResponse response, String encoding){
        if(encoding != null){
            response.setCharacterEncoding(encoding);
        }else{
            response.setCharacterEncoding(encoding_utf8);
        }
        response.setContentType("application/json");
    }

    /**
     * 响应成功结果的相同框架
     */
    private static Map<String, Object> CommonResp(){
        Map<String, Object> resp = new HashMap<>();
        resp.put(code, CodeEnum.SUCCESS.code);
        resp.put(message, CodeEnum.SUCCESS.description);
        resp.put(result, "");
        resp.put(state, true);
        return resp;
    }


    /**
     * 获取请求参数中有效的Integer参数
     * @param reqData json对象
     * @param param json中的参数名
     * @param message 错误消息
     */
    public static Integer getValidateParamInt(JSONObject reqData, String param, String message){
        Integer paramInt = reqData.getInteger(param);
        if(paramInt == null){
            throw new BusinessException(message);
        }
        return paramInt;
    }

    /**
     * 获取请求参数中有效的String参数
     * @param reqData json对象
     * @param param json中的参数名
     * @param message 错误消息
     */
    public static String getValidateParamStr(JSONObject reqData, String param, String message){
        String paramStr = reqData.getString(param);
        if(paramStr == null){
            throw new BusinessException(message);
        }
        return paramStr;
    }

    /**
     * 获取请求参数中有效的Date参数
     * @param reqData json对象
     * @param param json中的参数名
     * @param message 错误消息
     */
    public static Date getValidateParamDate(JSONObject reqData, String param, String message){
        Date paramDate = reqData.getDate(param);
        if(paramDate == null){
            throw new BusinessException(message);
        }
        return paramDate;
    }

}
